package com.atguigu.app.dws;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.bean.TradePaymentWindowBean;
import com.atguigu.util.DateFormatUtil;
import com.atguigu.util.KafkaUtil;
import com.atguigu.util.MyClickHouseUtil;
import com.google.inject.internal.cglib.core.$DefaultGeneratorStrategy;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AllWindowedStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import scala.tools.nsc.doc.model.Val;

import java.time.Duration;

/**
 * @author hfh
 * @version 1.0
 * @date 2022/8/25 17:15
 */
public class DwsTradePaymentSucWindow {
    public static void main(String[] args) throws Exception {
        //获取环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //设置状态后端
        /*env.enableCheckpointing(5*60*1000L, CheckpointingMode.EXACTLY_ONCE);
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
        env.getCheckpointConfig().setCheckpointTimeout(3*60*1000L);
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
        System.setProperty("HADOOP_USER_NAME","atguigu");*/

        //TODO 1 从Kafka中读取支付成功明细主题数据  dwd_trade_pay_detail_suc
        String topicName = "dwd_trade_pay_detail_suc";
        String groupId = "dws_trade_payment_suc_window";
        DataStreamSource<String> streamSource = env.addSource(KafkaUtil.getKafkaConsumer(topicName, groupId));


        //TODO 2 转换数据结构为json
        SingleOutputStreamOperator<JSONObject> jsonStream= streamSource.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                try {
                    JSONObject jsonObject = JSONObject.parseObject(value);
                    out.collect(jsonObject);
                } catch (Exception e) {

                }
            }
        });
        //TODO 3 设置水位线 按照user_id分组
        SingleOutputStreamOperator<JSONObject> timestampsAndWatermarks = jsonStream.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2L))
                .withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
                    @Override
                    public long extractTimestamp(JSONObject element, long recordTimestamp) {
                        return element.getLong("ts") * 1000L;
                    }
                }));

        KeyedStream<JSONObject, String> keyedStream = timestampsAndWatermarks.keyBy(new KeySelector<JSONObject, String>() {
            @Override
            public String getKey(JSONObject value) throws Exception {
                return value.getString("user_id");
            }
        });

        //TODO 4 统计独立支付人数和首次支付新人
        SingleOutputStreamOperator<TradePaymentWindowBean> flatmap = keyedStream.flatMap(new RichFlatMapFunction<JSONObject, TradePaymentWindowBean>() {
            private ValueState<String> valueState = null;

            @Override
            public void open(Configuration parameters) throws Exception {
                valueState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastPayDt", String.class));
            }

            @Override
            public void flatMap(JSONObject value, Collector<TradePaymentWindowBean> out) throws Exception {
                Long ts = value.getLong("ts") * 1000;
                String lastDt = DateFormatUtil.toDate(ts);
                String lastPayDt = valueState.value();
                Long paymentSucUniqueUserCount = 0L;
                Long paymentSucNewUserCount = 0L;
                if (lastPayDt == null) {
                    valueState.update(lastDt);
                    paymentSucNewUserCount = 1L;
                    paymentSucUniqueUserCount = 1L;
                } else {
                    if (!lastDt.equals(lastPayDt)) {
                        valueState.update(lastDt);
                        paymentSucUniqueUserCount = 1L;
                    }
                }

                if (paymentSucNewUserCount == 1L || paymentSucUniqueUserCount == 1L) {
                    out.collect(new TradePaymentWindowBean("", "", paymentSucUniqueUserCount, paymentSucNewUserCount, ts));
                }
            }
        });


        //TODO 5 开窗聚合
        AllWindowedStream<TradePaymentWindowBean, TimeWindow> windowedStream = flatmap.windowAll(TumblingEventTimeWindows.of(Time.seconds(10L))).allowedLateness(Time.seconds(2L));

        SingleOutputStreamOperator<TradePaymentWindowBean> reduce = windowedStream.reduce(new ReduceFunction<TradePaymentWindowBean>() {
            @Override
            public TradePaymentWindowBean reduce(TradePaymentWindowBean value1, TradePaymentWindowBean value2) throws Exception {
                value1.setPaymentSucUniqueUserCount(value1.getPaymentSucUniqueUserCount() + value2.getPaymentSucUniqueUserCount());
                value1.setPaymentSucNewUserCount(value1.getPaymentSucNewUserCount() + value2.getPaymentSucNewUserCount());
                return value1;
            }
        }, new AllWindowFunction<TradePaymentWindowBean, TradePaymentWindowBean, TimeWindow>() {
            @Override
            public void apply(TimeWindow window, Iterable<TradePaymentWindowBean> values, Collector<TradePaymentWindowBean> out) throws Exception {
                TradePaymentWindowBean next = values.iterator().next();
                next.setStt(DateFormatUtil.toYmdHms(window.getStart()));
                next.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                out.collect(next);
            }
        });
        reduce.print("reduce>>>>>");

        //TODO 6 写出到ClickHouse
        reduce.addSink(MyClickHouseUtil.<TradePaymentWindowBean>getSink("insert into dws_trade_payment_suc_window values(?,?,?,?,?)"));

        env.execute(groupId);
    }
}
